<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>关系链可视化系统</h2>
        <p>{{isLogin ? '用户登录' : '用户注册'}}</p>
      </div>

      <!-- 登录表单 -->
      <el-form v-if="isLogin" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名或邮箱"
            prefix-icon="el-icon-user"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="el-icon-lock"
            size="large"
            show-password
            @keyup.enter.native="handleLogin"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form v-else ref="registerForm" :model="registerForm" :rules="registerRules" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="用户名"
            prefix-icon="el-icon-user"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="邮箱"
            prefix-icon="el-icon-message"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="full_name">
          <el-input
            v-model="registerForm.full_name"
            placeholder="真实姓名"
            prefix-icon="el-icon-s-custom"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="el-icon-lock"
            size="large"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="确认密码"
            prefix-icon="el-icon-lock"
            size="large"
            show-password
            @keyup.enter.native="handleRegister"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 切换登录/注册 -->
      <div class="switch-form">
        <span v-if="isLogin">
          还没有账号？
          <el-button type="text" @click="isLogin = false">立即注册</el-button>
        </span>
        <span v-else>
          已有账号？
          <el-button type="text" @click="isLogin = true">立即登录</el-button>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { authAPI } from '@/api'

export default {
  name: 'Login',
  data() {
    // 确认密码验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      isLogin: true,
      loading: false,

      // 登录表单
      loginForm: {
        username: '',
        password: ''
      },

      // 注册表单
      registerForm: {
        username: '',
        email: '',
        full_name: '',
        password: '',
        confirmPassword: ''
      },

      // 登录验证规则
      loginRules: {
        username: [
          { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },

      // 注册验证规则
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },

  mounted() {
    // 检查是否已登录
    this.checkLogin()
  },

  methods: {
    // 检查登录状态
    checkLogin() {
      const token = localStorage.getItem('auth_token')
      if (token) {
        // 验证token有效性
        authAPI.verifyToken(token).then(response => {
          if (response.code === 200 && response.data.valid) {
            // token有效，直接跳转到主页
            this.$router.push('/')
          }
        }).catch(() => {
          // token无效，清除本地存储
          localStorage.removeItem('auth_token')
          localStorage.removeItem('user_info')
        })
      }
    },

    // 处理登录
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            const response = await authAPI.login(this.loginForm)
            if (response.code === 200) {
              // 保存token和用户信息
              localStorage.setItem('auth_token', response.data.token)
              localStorage.setItem('user_info', JSON.stringify(response.data.user))

              this.$message.success('登录成功')

              // 跳转到主页
              this.$router.push('/')
            } else {
              this.$message.error(response.message || '登录失败')
            }
          } catch (error) {
            console.error('Login error:', error)
            const message = error.response?.data?.message || '登录失败，请稍后重试'
            this.$message.error(message)
          } finally {
            this.loading = false
          }
        }
      })
    },

    // 处理注册
    handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            const registerData = {
              username: this.registerForm.username,
              email: this.registerForm.email,
              full_name: this.registerForm.full_name,
              password: this.registerForm.password
            }

            const response = await authAPI.register(registerData)
            if (response.code === 201) {
              this.$message.success('注册成功，请登录')

              // 切换到登录表单
              this.isLogin = true

              // 清空注册表单
              this.registerForm = {
                username: '',
                email: '',
                full_name: '',
                password: '',
                confirmPassword: ''
              }

              // 将用户名填入登录表单
              this.loginForm.username = registerData.username
            } else {
              this.$message.error(response.message || '注册失败')
            }
          } catch (error) {
            console.error('Register error:', error)
            const message = error.response?.data?.message || '注册失败，请稍后重试'
            this.$message.error(message)
          } finally {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.switch-form {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.switch-form .el-button--text {
  padding: 0;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }

  .login-box {
    padding: 30px 20px;
  }
}
</style>